﻿using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;

[CustomEditor(typeof(CreateCubMesh))]
public class CubeMeshEditor : Editor
{

    //按钮内容
    private GUIContent _createButtonContent;
    private GUIContent _saveButtonContent;
    private GUIContent _clearButtonContent;
    private CreateCubMesh _meshCreator;



    private void OnEnable()
    {
        _meshCreator = target as CreateCubMesh; 
        if (_meshCreator == null || EditorApplication.isPlaying)
        {
            return;
        }

        if (_createButtonContent == null)
        {
            _createButtonContent = new GUIContent("Create", "创建一个初始方块");
        }

        if(_saveButtonContent == null)
        {
            _saveButtonContent = new GUIContent("Save", "保存编辑中的Mesh");
        }

        if (_clearButtonContent == null)
        {
            _clearButtonContent = new GUIContent("Clear", "清楚当前编辑的Mesh");
        }

        

        _meshCreator.Init();

    }

    private void OnDisable()
    {
        _meshCreator = null;
    }


    public override void OnInspectorGUI()
    {
       // GUI.enabled = _meshMaker.IsCanEdit;

#region 编辑模式选择
        EditorGUILayout.BeginHorizontal();
        if (GUILayout.Button(_createButtonContent, GUILayout.Height(20), GUILayout.Width(45)))
        {
            Debug.Log("Edit test ....");
            int childCount = _meshCreator.gameObject.transform.childCount;
            _meshCreator.CreateAWrapCube(childCount, 100f, 100f, 10f, 10, 10);
        }

        if (GUILayout.Button(_saveButtonContent, GUILayout.Height(20), GUILayout.Width(45)))
        {
            SaveMesh();
        }

        if (GUILayout.Button(_clearButtonContent, GUILayout.Height(20), GUILayout.Width(45)))
        {
            _meshCreator.Clear();
        }


        

        GUI.color = Color.white;
        EditorGUILayout.EndHorizontal();

#endregion

    }

    /// <summary>
    /// 保存Mesh数据
    /// </summary>
    private void SaveMesh()
    {

        string path = EditorUtility.SaveFilePanel("Save Mesh", Application.dataPath, "New Mesh", "asset");

        if (path.Length != 0)
        {
            string subPath = path.Substring(0, path.IndexOf("Asset"));
            path = path.Replace(subPath, "");
            //MeshFilter meshfileter = _meshCreator.gameObject.GetComponent<MeshFilter>();
            AssetDatabase.CreateAsset(_meshCreator.GetRootMesh(), path);
            AssetDatabase.SaveAssets();
        }

    }
}
